package com.swift.violent.mainstay.config.handler;

import com.swift.violent.mainstay.common.constants.ResultCode;
import com.swift.violent.mainstay.common.lang.CommonResultOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理器
 *
 * @author ruoyi
 */
@Slf4j
@RestControllerAdvice
public class GlobalFirstExceptionHandler {
    /**
     * 顶级异常
     * Handle exception object.
     *
     * @param e the e
     *
     * @return the object
     */
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        log.error("顶级异常", e);
        return CommonResultOutput.commonErrorOutput(ResultCode.INTERNAL_ERROR.code, e.getMessage());
    }

    /**
     * Http消息不可读异常
     * Http message not readable exception object.
     *
     * @param e the e
     *
     * @return the object
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Object httpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("Http消息不可读异常", e);
        return CommonResultOutput.commonErrorOutput(ResultCode.BAD_REQUEST.code, "请核查参数");
    }

    /**
     * 参数验证异常
     *
     * @param e the e
     *
     * @return the object
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数验证异常", e);
        return CommonResultOutput.commonErrorOutput(ResultCode.BAD_REQUEST.code, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    /**
     * 运行异常
     * Runtime exception object.
     *
     * @param e the e
     *
     * @return the object
     */
    @ExceptionHandler(RuntimeException.class)
    public Object runtimeException(RuntimeException e) {
        log.error("运行异常", e);
        return CommonResultOutput.commonErrorOutput(ResultCode.BAD_REQUEST.code, e.getMessage());
    }

}
